//
//  XXButonSegment.m
//  WangLottery
//
//  Created by 黄修勇 on 12-5-19.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "XXButonSegment.h"

@implementation XXButonSegment


@synthesize selectIndex=_selectIndex;

@synthesize numberOfItem=_numberOfItem;
@synthesize itemMargin=_itemMargin;


-(void)dealloc{

    [viewItems release];
    [super dealloc];
}

-(void)layoutSubviews{

    if (!viewItems) {
        return;
    }
    
    float itemWidth=(self.frame.size.width-(viewItems.count-1)*_itemMargin)/viewItems.count;
    
    for (int i=0; i<viewItems.count; i++) {
        UIView *view=[viewItems objectAtIndex:i];
        view.frame=CGRectMake((itemWidth+_itemMargin)*i, 0.0f, itemWidth, self.frame.size.height);
    }
}

-(id)initwithItem:(NSArray *)items{

    self=[super initWithFrame:CGRectZero];
    
    if (self) {
        
        viewItems=[NSMutableArray new];
        
        normalImg=[UIImage imageNamed:@"btn_red_150_65.png"];
        selectImg=[UIImage imageNamed:@"btn_red_yellow_160_65.png"];
        
        for (int i=0; i<items.count; i++) {
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
            btn.tag=i;
            [btn setBackgroundImage:normalImg forState:UIControlStateNormal];
            [btn setBackgroundImage:selectImg forState:UIControlStateSelected];
            [btn setTitle:[items objectAtIndex:i] forState:UIControlStateNormal];
            [self addSubview:btn];
            btn.titleLabel.font=[UIFont boldSystemFontOfSize:14.0f];
            [btn addTarget:self action:@selector(btnDone:) forControlEvents:UIControlEventTouchUpInside];
            [viewItems addObject:btn];
        }
        _numberOfItem=viewItems.count;
        _selectIndex=-1;
    }
    return self;
}

-(void)setSelectIndex:(NSInteger)selectIndex{

    if (selectIndex==_selectIndex||selectIndex>=_numberOfItem) {
        return;
    }
    
    UIButton *btn;

    if (_selectIndex>=0) {
        UIButton *btn=[viewItems objectAtIndex:_selectIndex];
        btn.selected=NO;
    }
    
    _selectIndex=selectIndex;
    btn=[viewItems objectAtIndex:_selectIndex];
    btn.selected=YES;
}

-(void)setItemMargin:(float)itemMargin{

    if (itemMargin==_itemMargin) {
        return;
    }
    
    _itemMargin=itemMargin;
    [self layoutSubviews];
}

-(void)btnDone:(UIButton *)btn{

    if (btn.selected==YES) {
        return;
    }
    
    self.selectIndex=btn.tag;
    [self sendActionsForControlEvents:UIControlEventValueChanged];  
}

@end
